package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate   redisTemplate;

    /**
     * 发送短信验证码
     * 在某个意义上,Map~POJO
     */
    @PostMapping("/sendMsg")
    public R<String> senMsg(@RequestBody User user, HttpSession session) {
        //1.获取手机号
        String phone = user.getPhone();
        //2.生成随机验证码，并存入session中；
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("code={}",code);
        //session.setAttribute("code",code);

        redisTemplate.opsForValue().set("code_"+phone,code,120, TimeUnit.SECONDS);
        //3.调用工具类发送短信
        //SMSUtils.sendSms(phone,code);
        return R.success("发送成功");
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession session) {
        //    1.获取手机号，验证码
        String phone = map.get("phone");
        String code1 = map.get("code");

        //    2.对比验证码
        //String code2 = (String) session.getAttribute("code");

        String code2 = (String) redisTemplate.opsForValue().get("code_" + phone);
        boolean flag = StringUtils.equals(code1, code2);
        if (!flag) {
            //    验证码错误
            return R.error("验证码错误");
        }

        //    3.判断用户是否是新用户，
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            //    新用户
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);//用户状态
            userService.save(user);
        }
        session.setAttribute("user",user.getId());
        //    4.登录成功

        redisTemplate.delete("code_"+phone);
        return R.success(user);
    }
}
